package com.businesscard.system.controller;

import com.businesscard.system.entity.User;
import com.businesscard.system.service.UserService;
import com.businesscard.system.util.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "user/login";
    }

    /**
     * 用户登录处理
     */
    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestBody User user, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 验证验证码
        String captcha = (String) session.getAttribute("captcha");
        if (captcha == null || !captcha.equalsIgnoreCase(user.getCaptcha())) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return result;
        }

        // 验证用户名和密码
        User loginUser = userService.login(user.getUsername(), user.getPassword());
        if (loginUser != null) {
            // 登录成功，保存用户信息到session
            session.setAttribute("user", loginUser);
            session.removeAttribute("captcha");

            result.put("success", true);
            result.put("message", "登录成功");
            result.put("user", loginUser);
            result.put("redirectUrl", "/user/businesscard");
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }

        return result;
    }

    /**
     * 用户注册页面
     */
    @GetMapping("/register")
    public String registerPage(Model model) {
        model.addAttribute("user", new User());
        return "user/register";
    }

    /**
     * 用户注册处理
     */
    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(@RequestBody @Valid User user, BindingResult bindingResult, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 参数校验
        if (bindingResult.hasErrors()) {
            result.put("success", false);
            result.put("message", bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }

        // 验证验证码
        String captcha = (String) session.getAttribute("captcha");
        if (captcha == null || !captcha.equalsIgnoreCase(user.getCaptcha())) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return result;
        }

        // 验证两次密码是否一致
        if (!user.getPassword().equals(user.getConfirmPassword())) {
            result.put("success", false);
            result.put("message", "两次密码不一致");
            return result;
        }

        // 注册用户
        boolean success = userService.register(user);
        if (success) {
            result.put("success", true);
            result.put("message", "注册成功");
            session.removeAttribute("captcha");
        } else {
            result.put("success", false);
            result.put("message", "注册失败，用户名或邮箱已存在");
        }

        return result;
    }

    /**
     * 用户注销
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/user/login";
    }

    /**
     * 忘记密码页面
     */
    @GetMapping("/forget-password")
    public String forgetPasswordPage() {
        return "user/forget-password";
    }

    /**
     * 忘记密码处理
     */
    @PostMapping("/forget-password")
    @ResponseBody
    public Map<String, Object> forgetPassword(@RequestParam String email, @RequestParam String captcha, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 验证验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return result;
        }

        // 重置密码
        boolean success = userService.resetPassword(email);
        if (success) {
            result.put("success", true);
            result.put("message", "临时密码已发送到您的邮箱，请查收");
            session.removeAttribute("captcha");
        } else {
            result.put("success", false);
            result.put("message", "邮箱不存在");
        }

        return result;
    }

    /**
     * 修改密码页面
     */
    @GetMapping("/change-password")
    public String changePasswordPage(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        return "user/change-password";
    }

    /**
     * 修改密码处理
     */
    @PostMapping("/change-password")
    @ResponseBody
    public Map<String, Object> changePassword(@RequestParam String oldPassword, @RequestParam String newPassword,
                                             @RequestParam String confirmPassword, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        User user = (User) session.getAttribute("user");
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return result;
        }

        // 验证两次密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            result.put("success", false);
            result.put("message", "两次密码不一致");
            return result;
        }

        // 修改密码
        boolean success = userService.changePassword(user.getId(), oldPassword, newPassword);
        if (success) {
            result.put("success", true);
            result.put("message", "密码修改成功");
            // 修改成功后退出登录
            session.invalidate();
        } else {
            result.put("success", false);
            result.put("message", "旧密码错误");
        }

        return result;
    }

    /**
     * 验证码生成
     */
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String captcha = CaptchaUtil.generateCaptcha(request, response);
        // 保存到session
        session.setAttribute("captcha", captcha);
    }

    /**
     * 个人中心页面
     */
    @GetMapping("/profile")
    public String profilePage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        model.addAttribute("user", user);
        return "user/profile";
    }
}



